package tgc.edu.yzy.web.admin.controller;

import java.util.HashMap;
import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.yzy.custom.DatagridUtils;
import tgc.edu.yzy.entity.Record;
import tgc.edu.yzy.service.RecordService;

@Controller
@RequestMapping(value="admin/record")
public class RecordController {
	@Autowired
	private RecordService recordservice;
	
	@RequestMapping(value="record")
	private String record() {
		return "admin/record/record";
	}
	
	@RequestMapping(value="pagelist")
	@ResponseBody
	private Object pagelist(DatagridUtils form,Record record,String bookname,String username) {
		Pageable pageable=form.buildPageable();
		Page<Record> books=null;
		
		Specification<Record> spec = new Specification<Record>() {

			@Override
			public Predicate toPredicate(Root<Record> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(record.getName())) {
					rules.add(criteriaBuilder.like(root.get("name"), "%"+record.getName()+"%"));
				}else if(StringUtils.hasText(record.getTime())) {
					rules.add(criteriaBuilder.like(root.get("time"), record.getTime()+"%"));
				}else if(StringUtils.hasText(record.getContent())) {
					rules.add(criteriaBuilder.like(root.get("content"), "%"+record.getContent()+"%"));
				}else if(StringUtils.hasText(bookname)) {
					rules.add(criteriaBuilder.like(root.get("book").get("name"), "%"+bookname+"%"));
				}else if(StringUtils.hasText(username)) {
					rules.add(criteriaBuilder.like(root.get("user").get("name"), "%"+username+"%"));
				}
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		books= recordservice.findAll(spec,pageable);
		HashMap<String , Object> result = form.getPageResult(books);
		return result; 
	}
}
